package router

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"sdn-executor/api/controller"
	"sdn-executor/api/middlewares"
	"strings"
	"time"
)

func AddRoutes(e *gin.Engine) {
	// no route
	e.NoRoute(noRoute)

	// openAPI
	apiGroup := e.Group("/api/v1", middlewares.JSONResponse(), middlewares.HandleTimeout(300*time.Second))
	{
		g1 := apiGroup.Group("/cli")
		{
			g1.POST("/command", controller.ExecuteCLICmd)
			g1.GET("/result/:requestId", controller.GetCLIResultByRequestID)
		}

		g2 := apiGroup.Group("/netconf")
		{
			g2.POST("/command", controller.ExecuteNetconfCmd)
			g2.GET("/result/:requestId", controller.GetNetconfResultByRequestID)
		}

		g3 := apiGroup.Group("/gnmi")
		{
			g3.POST("/capability", controller.ExecuteGNMICapCmd)
			g3.POST("/get", controller.ExecuteGNMIGetCmd)
			g3.POST("/update", controller.ExecuteGNMIUpdateCmd)
			g3.POST("/replace", controller.ExecuteGNMIReplaceCmd)
			g3.POST("/delete", controller.ExecuteGNMIDeleteCmd)
			g3.GET("/result/:requestId", controller.GetGNMIResultByRequestID)
		}

		g4 := apiGroup.Group("/snmp")
		{
			g4.POST("/get", controller.ExecuteSNMPGetCmd)
			g4.POST("/getnext", controller.ExecuteSNMPGetNextCmd)
			g4.POST("/getbulk", controller.ExecuteSNMPGetBulkCmd)
			g4.POST("/bulkwalk", controller.ExecuteSNMPBulkWalkCmd)
			g4.POST("/walk", controller.ExecuteSNMPWalkCmd)
		}

		e.GET("/health", func(c *gin.Context) {
			c.JSON(200, "OK")
		})

	}

	// static
	// r.Static("/", "../../frontend/webfront/shop-admin/dist")
}

func noRoute(c *gin.Context) {
	mtype := "*"
	accept := c.GetHeader("Accept")
	accept = strings.ToLower(accept)
	if strings.Contains(accept, "text") {
		mtype = "text"
	} else if strings.Contains(accept, "json") {
		mtype = "json"
	} else if strings.Contains(accept, "xml") {
		mtype = "xml"
	}

	if mtype == "*" {
		contentType := c.GetHeader("Content-Type")
		contentType = strings.ToLower(contentType)
		if strings.Contains(contentType, "text") {
			mtype = "text"
		} else if strings.Contains(contentType, "json") {
			mtype = "json"
		} else if strings.Contains(contentType, "xml") {
			mtype = "xml"
		}
	}

	if mtype == "json" {
		c.Header("Content-Type", "application/json")
		c.JSON(http.StatusNotFound, &controller.Response{Code: http.StatusNotFound, Msg: "No Request Path Exist"})
	} else if mtype == "xml" {
		c.Header("Content-Type", "application/xml")
		c.XML(http.StatusNotFound, "<response><code>404</code><Message>No Request Path Exist</Message></response>")
	} else {
		c.String(http.StatusNotFound, "No Request Path Exist")
	}
}
